<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .box {
        width: 100px;
        height: 100px;
        background-color: cyan;
        position: absolute;
        left: 0;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <script>
      //事件: 1.鼠标按下: onmousedown  2.鼠标移动 onmousemove  3.鼠标抬起: onmouseup
      var boxELe = document.querySelector(".box"); //获取box盒子
      boxELe.onmousedown = function (e) {
        //鼠标按下box盒子的时候
        // console.log("按下了a");
        var x = e.clientX - boxELe.offsetLeft; //算出鼠标按下之后的x轴位置 - box盒子原本的距离浏览器最左边的距离
        var y = e.clientY - boxELe.offsetTop;
        document.onmousemove = function (e) {
          //鼠标移动的时候
          //   console.log("拖动了")
          var xx = e.clientX;
          var yy = e.clientY;
          var res1 = xx - x;
          var res2 = yy - y;
          boxELe.style.left = res1 + "px";
          boxELe.style.top = res2 + "px";
        };
        document.onmouseup = function (e) {
          document.onmousemove = "";
        };
      };
    </script>
  </body>
</html>
